package cn.tedu.straw.gateway.security;

import cn.tedu.straw.commons.security.LoginUserInfo;
import cn.tedu.straw.gateway.service.IUserService;
import cn.tedu.straw.gateway.vo.PermissionVO;
import cn.tedu.straw.gateway.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 调用业务层根据登录时填写的手机号查询数据库中的数据
        UserLoginVO userLoginVO = userService.loginByPhone(s);

        // 如果手机号没有对应的数据，则直接返回null，登录将失败
        if (userLoginVO == null) {
            return null;
        }

        // 从查询结果中取出权限数据，封装为Spring Security需要的类型
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<PermissionVO> permissions = userLoginVO.getPermissions();
        for (PermissionVO permission : permissions) {
            String authority = permission.getAuthority();
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority);
            authorities.add(grantedAuthority);
        }

        // 创建LoginUserInfo对象，准备作为返回给Spring Security的对象
        LoginUserInfo loginUserInfo = new LoginUserInfo(
                userLoginVO.getPhone(),
                userLoginVO.getPassword(),
                userLoginVO.getIsEnabled() == 1,
                true,
                true,
                userLoginVO.getIsLocked() == 0,
                authorities
        );
        loginUserInfo.setUserId(userLoginVO.getId());
        loginUserInfo.setNickName(userLoginVO.getNickName());

        // 返回
        return loginUserInfo;
    }

}
